package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

@Component
public class CacheClient {


    private final StringRedisTemplate stringRedisTemplate;

    //通过构造函数将 stringRedisTemplate 引入
    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    // 创建线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);


    public void set(String key, Object value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

    /**
     * 设置逻辑过期
     *
     * @param key
     * @param value
     * @param time
     * @param unit
     */
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit) {
        //设置逻辑过期
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        //写入 redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    /**
     * 缓存击穿抽象方法
     * @param keyPrefix
     * @param id
     * @param type
     * @param dbFallback  传入方法编程
     * @param <R>       返回值
     * @param <ID>      参数
     */
    public <R, ID> R queryWithPassThrough(
            String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        //1.从redis中查找缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        if (StrUtil.isNotBlank(json)) {
            //3.存在返回
            return JSONUtil.toBean(json, type);
        }
        //判断是否为空值
        if (json != null) {
            return null;
        }
        //4.不存在,根据id进行数据库查询
        R r = dbFallback.apply(id);

        //5.不存在返回错误
        if (type == null) {
            //将空值写入redis中 --- 防止缓存穿透对未查询到的数据保存空值
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //6.存在写入redis -- 调用该类方法
        this.set(key,r,time,unit);
        // 7.返回
        return r;
    }


    //使用redis中的setnx  进行加锁
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.MINUTES);
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }


    /**
     *  添加逻辑过期 解决缓存击穿问题
     * @param keyPrefix
     * @param id
     * @param type
     * @param dbFallback
     * @param time
     * @param unit
     * @return
     * @param <ID>
     * @param <R>
     */
    public <ID,R> R queryWithExpire( String keyPrefix,ID id,Class<R> type,Function<ID, R> dbFallback, Long time, TimeUnit unit){
        String key = keyPrefix + id;
        //1.从redis中查找缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        if (StrUtil.isBlank(json)){
            //3.不存在返回
            return  null;
        }
        //4.将json数据反序列化成对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        //5.存在判断缓存是否过期
        if (expireTime.isAfter(LocalDateTime.now())){
            //5.1 未过期返回商品信息
            return r;
        }
        //5.2 过期缓存重建
        //6 缓存重建
        //6.1 获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        boolean tryLock = tryLock(lockKey);
        //6.2 判断是否获取成功
        if (tryLock){
            //6.3 成功，开启独立线程 重建缓存
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    //重建缓存
                    //查数据库
                    R r1 = dbFallback.apply(id);
                    //写入Redis
                    this.setWithLogicalExpire(key,r1,time,unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放锁
                    unlock(lockKey);
                }
            });
        }
        //6.4 失败，返回过期店铺信息
        return r;
    }





   /* public <R,ID> R queryWithMutex(
            String keyPrefix,ID id,Class<R> type,Function<ID, R> dbFallback, Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        //1.从redis中查找缓存
        String json = stringRedisTemplate.opsForValue().get(key);
        //2.判断是否存在
        if (StrUtil.isNotBlank(json)) {
            //3.存在返回
            return JSONUtil.toBean(json, type);
        }

        //判断命中的是否是空值
        if (json != null) {
            //返回一个错误信息
            return null;
        }
        //4.实现缓存重建
        String lockkey = LOCK_SHOP_KEY + id;
        R r;
        try {
            //4.1 获取互斥锁
            boolean tryLock = tryLock(lockkey);
            //4.2 判断是否获取成功
            if (!tryLock) {
                //4.3 失败，则休眠并重试
                Thread.sleep(50);
                return queryWithMutex(keyPrefix, id, type, dbFallback, time, unit);
            }
            //4.4 成功，查询数据库
            r = dbFallback.apply(id);
            //模拟重建延迟
            Thread.sleep(200);
            //5.不存在返回错误
            if (r == null) {
                //将空值写入redis中 --- 防止缓存穿透对未查询到的数据保存空值
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //6.存在写入redis
            this.set(key, r, time, unit);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //7.释放互斥锁
            unlock(lockkey);
        }
        //8.返回
        return r;
    }*/






}